<template>
  <div class="newVs">
    <div class="mask"></div>
    <div class="new_vs">
      <div class="vs-top">
        <p>{{!$route.query.oid ? '新建资料（厂商进货）':'厂商进货补单'}}</p>
        <i class="el-icon-close" @click="closeNewClerk"></i>
      </div>
      <div class="vs-info">
        <div class="vs-info-1">
          <p>进货日期</p>
          <el-date-picker v-model="inputDate" type="date" value-format="yyyy-MM-dd HH:mm:ss" disabled></el-date-picker>
          <p>厂商编号</p>
          <div class="infoBox">
            <el-input v-model="manufacturerNo" @blur="manufacturerNoBlur" :disabled="supplement"></el-input>
            <el-select v-model="manufacturerName" @change="manufacturerNameChange" :disabled="supplement">
              <el-option v-for="item in manufacturerList" :key="item.value" :label="item.label" :value="item.value">
                <span style="float:left">{{item.value}}</span>
                <span style="float:right">{{item.label}}</span>
              </el-option>
            </el-select>
          </div>
          <p>单号</p>
          <el-input v-model="odd" :disabled="supplement"></el-input>
          <p>厂进序号</p>
          <el-input v-model="inputSequence" disabled></el-input>
        </div>
        <div class="vs-info-2">
          <p>收货仓库</p>
          <div class="infoBox">
            <el-input v-model="inputWarehouseNo" @blur="inputWarehouseNoBlur" :disabled="supplement"></el-input>
            <el-select v-model="inputWarehouseName" @change="e=>{this.inputWarehouseNo=e}" :disabled="supplement">
              <el-option v-for="item in warehouseList" :key="item.value" :label="item.label" :value="item.value">
                <span style="float:left">{{item.value}}</span>
                <span style="float:right">{{item.label}}</span>
              </el-option>
            </el-select>
          </div>
          <p>公司仓库</p>
          <div class="infoBox">
            <el-input v-model="companyNo" @blur="companyNoBlur" :disabled="supplement"></el-input>
            <el-select v-model="companyName" @change="e=>{this.companyNo=e}" :disabled="supplement">
              <el-option v-for="item in warehouseList" :key="item.value" :label="item.label" :value="item.value">
                <span style="float:left">{{item.value}}</span>
                <span style="float:right">{{item.label}}</span>
              </el-option>
            </el-select>
          </div>
          <p>配货方式</p>
          <el-select v-model="cooperateWay" :disabled="supplement">
            <el-option v-for="item in cooperateWayList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <p>折数</p>
          <el-input v-model="discount" :disabled="supplement"></el-input>
        </div>
        <el-table id="codeTable" border :data="codeData" class="tb-edit" style="width: 100%;margin-bottom:15px" max-height="148px" @cell-click="cellClick" :header-cell-style="{background:'#f4f4f4',padding:0,height:'40px'}" :cell-style="{padding:0,height:'36px'}">
          <el-table-column :label="header" width="150"></el-table-column>
          <el-table-column prop="colorName" label="颜色" width="100"></el-table-column>
          <template v-for="i in sizeList">
            <el-table-column :prop="i" :label="i" :key="i+Math.random()">
              <template slot-scope="scope">
                <el-input size="small" class="innerInp" v-model="scope.row[i]" @blur="handleInputBlurResult($event,{index:scope.$index,key:i,result:scope.row[i]})" @keyup.enter.native="inpEnter"></el-input>
              </template>
            </el-table-column>
          </template>
        </el-table>
        <div class="barcode">
          <p>条码扫描</p>
          <el-switch v-model="isBarcode" active-color="#409EFF" inactive-color="#C0C4CC" :disabled="creating"></el-switch>
          <div v-show="isBarcode">
            <p>条码选择</p>
            <el-radio :disabled="!isBarcode || creating" v-model="radio" label="1">货号码</el-radio>
            <el-radio :disabled="!isBarcode || creating" v-model="radio" label="2">ID码</el-radio>
          </div>
        </div>
        <div class="barcode-info-1" v-show="isBarcode">
          <p>品牌</p>
          <el-select v-model="brand" :disabled="!isBarcode">
            <el-option v-for="item in brandList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <p>款号</p>
          <el-input :disabled="!isBarcode" v-model="styleNumber"></el-input>
          <p>色号(位)</p>
          <el-input :disabled="!isBarcode" v-model="colorNumber" class="shortInp"></el-input>
          <p>验证码(位)</p>
          <el-input :disabled="!isBarcode" v-model="code" class="shortInp"></el-input>
          <p>季度</p>
          <el-autocomplete clearable v-model="quarter" :fetch-suggestions="queryQuarterList"></el-autocomplete>
        </div>
        <div class="barcode-info-2" v-show="isBarcode">
          <p>品名</p>
          <el-select v-model="name" :disabled="!isBarcode">
            <el-option v-for="item in nameList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <p>厂商售价</p>
          <el-input :disabled="!isBarcode" v-model="vendorPrice"></el-input>
          <p>条码样式</p>
          <el-input class="longInp" :disabled="!isBarcode" v-model="barcodeStyle"></el-input>
          <p>颜色</p>
          <div class="colorBox">
            <el-input :disabled="!isBarcode" v-model="colorNo" @blur="colorNoBlur"></el-input>
            <el-select v-model="colorName" :disabled="!isBarcode" @change="e=>{this.colorNo=e}">
              <el-option v-for="item in colorList" :key="item.no" :label="item.value" :value="item.no"></el-option>
            </el-select>
          </div>
        </div>
        <div class="enterBarcode">
          <el-input id="input1" v-model="barcode1" ref="barcodeInput" placeholder="扫描/输入货号或款号，输完按回车" @keyup.enter.native="barcodeEnter1($event)"></el-input>
          <el-input id="input" v-model="barcode2" ref="barcodeInput1" :disabled="!(isBarcode&&(radio==2))" placeholder="不一致的情况手输货号，输完按回车" @keyup.enter.native="barcodeEnter2($event)"></el-input>
          <span>合计：{{total}}</span>
        </div>
        
        <el-table v-loading="loading" height="328px" :data="barcodeData" style="width: 100%" :header-cell-style="{background:'#f4f4f4',padding:0,height:'40px'}" :cell-style="{padding:0,height:'36px'}">
          <el-table-column prop="kindsNumber" label="货号" width="250"></el-table-column>
          <el-table-column prop="colorName" label="颜色"></el-table-column>
          <el-table-column prop="sizeNo" label="尺码编号"></el-table-column>
          <el-table-column prop="sum" label="数量" width="100"></el-table-column>
          <el-table-column prop="onePrice" label="单价" width="100"></el-table-column>
          <el-table-column prop="sellingPrice" label="售价" width="100"></el-table-column>
          <el-table-column prop="manufacturerPrice" label="厂价" width="100">
            <template slot-scope="scope">
              <el-input size="small" v-model="scope.row.manufacturerPrice" @blur="mpBlur(scope.row)"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="commodityName" label="品名"></el-table-column>
        </el-table>
      </div>
      <div class="vs-btn">
        <el-button @click="closeNewClerk">关闭</el-button>
        <!-- <el-button plain type="primary" @click="saveNew_vs">保存</el-button> -->
        <el-button type="primary" @click="continueInput">继续录入</el-button></div>
      <!-- F7弹出框 -->
      <div class="popup" :style="{display:showPopup}">
        <div class="popup_t">
          <p>输入扫描数量</p>
          <i @click="closePopup" class="el-icon-close"></i>
        </div>
        <div class="popup_c">
          <p>请输入扫描数量</p>
          <p>如果不输入则扫描数量为1</p>
          <el-input v-model="scanNum" style="margin-top:10px" @keyup.enter="determine"></el-input>
          <!-- <input type="text" class="popup_button" v-model="scanNum" @keyup.enter="determine"> --></div>
        <div class="popup_b">
          <el-button @click="closePopup">取消</el-button>
          <el-button type="primary" @click="determine">确定</el-button></div>
      </div>
    </div>
  </div>
</template>

<script>
import { getManufacturer, getBarCode, factoryInput, searchKindsNumber, inputQuery, factoryInputScanner, updateMP} from '../../../../network/manufacturer'
import { getKindsNumberList, postKindsNumber, getArtNo } from '../../../../network/artNo'
import { getSize } from '../../../../network/size'
import { getBranded } from '../../../../network/branded'
import { getProductName } from '../../../../network/productName'
import { getQuarter, postQuarter } from '../../../../network/quarter'
import { getColorSeason } from '../../../../network/colorSeason'
import { existRfid } from '../../../../network/rfid'
import exportMethods from '../../../../components/mixins/exportMethods'

export default {
  mixins: [exportMethods],
  created(){
    getProductName().then(res => {
      if (res.data.code == 200) {
        let list = res.data.data
        list.forEach( e => {
          this.nameList.push({value:e.name,label:e.name,commodityTypeNo:e.commodityTypeNo})
        })
      }
    })

    getQuarter().then(res => {
      if (res.data.data) {
        res.data.data.forEach(e => {
          this.quarterList.push({id:e.id,value:e.name})
          this.quarterMap[e.name] = e.id
        })
      }
    })
  },
  props: {
    sendData: {
      type: Object,
      default: {}
    },
    supplementList: {
      type: Array,
      default: []
    },
    flag: {
      type: String,
      default: 'none'
    },
    Str: {
      type: String,
      default: ''
    }
  },
  data(){
    return {
      loading: false,
      // 部类
      commodityType: '',
      // 条码规律详情
      manufacturerBarCode: {},
      // 品牌公司
      brandedCompany: '',
      // 尺码
      knSize: '',
      knSizeList: {},
      knAllSize: [],

      quarter: '',
      quarterList: [],
      quarterMap: {},

      kindsNumberMap: {},

      showPopup:'none',
      inputDate: '',
      manufacturerNo: '',
      manufacturerName: '',
      manufacturerList: [],
      odd: '',
      inputSequence: '',
      inputWarehouseNo: '',
      inputWarehouseName: '',
      warehouseList: [],
      companyNo: '',
      companyName: '',
      cooperateWay:'配货',
      cooperateWayList:[
        {value:'配货',label:'配货'},
        {value:'订货',label:'订货'},
        {value:'订断',label:'订断'},
        {value:'追断',label:'追断'}
      ],
      discount: 10,
      header: '',
      sizeList: ['7', '9', '1', '3', '5', '7', 'F'],
      codeData: [],
      creating: false,
      isBarcode: false,
      radio: '1',
      brand: '',
      brandList: [],
      styleNumber: '',
      colorNumber: '',
      code: '',
      name: '',
      nameList: [],
      vendorPrice: '',
      barcodeStyle: '',
      colorNo: '',
      colorName: '',
      colorList: [],
      barcode1: '',
      barcode2: '',
      barcodeData: [],
      tmpBarcodeData: [],

      tmpData: {},
      scanNum: 1,
      beforeScanNum: 1,
      supplement: false,
      total: 0
    }
  },
  watch: {
    Str(a,b){
      console.log(a)
    },
    sendData(a,b){
      // console.log(a)
      this.inputSequence = a.inputSequence
      this.inputDate = a.inputDate
      this.manufacturerNo = a.manufacturerNo
      this.manufacturerName = a.manufacturerName
      this.manufacturerList = a.manufacturerList
      this.odd = a.odd
      this.brand = a.brand
      this.inputWarehouseNo = a.inputWarehouseNo
      this.inputWarehouseName = a.inputWarehouseName
      this.warehouseList = a.warehouseList
      this.companyNo = a.companyNo
      this.companyName = a.companyName
      this.cooperateWay = a.cooperateWay
      this.$forceUpdate()
    },
    flag(a,b){
      if (a == 'block') {
        this.total = 0
        if (this.creating) this.creating = false
        if (this.$route.query.oid) {
          this.supplement = true
          inputQuery(JSON.stringify({
            sequence: this.$route.query.oid,
            pageData: {
              page: 1,
              limit: 999
            }
          })).then(res => {
            let obj = res.data.data.resultList[0]
            this.discount = obj.discount
            this.barcodeData = []
            this.total = 0
            obj.detailVOList.forEach(e => {
              e.knInfo = e.kindsNumber
              e.kindsNumber = e.knInfo.kindsNumber
              e.colorName = e.knInfo.colorName
              e.colorNo = e.knInfo.colorNo
              e.size = e.knInfo.size
              e.sizeNo = e.knInfo.sizeNo
              e.commodityName = e.knInfo.commodityName
              e.brandedName = e.knInfo.brandedName
              e.initialSum = e.sum
              e.enteringTime = e.enteringTime + ' 12:00:00'
              e.purchaseTime = obj.purchaseTime.slice(0,10) + ' 12:00:00'
              e.oldMP = e.manufacturerPrice
              this.total += Number(e.sum)
              this.barcodeData.push(e)
              this.kindsNumberMap[e.kindsNumber] = e
            })
          })
        } else {
          this.inputSequence = ''
          this.supplement = false
        }
      }
    },
    barcode1(a,b){
      this.barcode1 = a.toUpperCase().trim()
    },
    barcode2(a,b){
      this.barcode2 = a.toUpperCase().trim()
    },
    manufacturerNo(a,b){
      this.manufacturerNo = a.toUpperCase().trim()
    },
    inputWarehouseNo(a,b){
      this.inputWarehouseNo = a.toUpperCase().trim()
    },
    companyNo(a,b){
      this.companyNo = a.toUpperCase().trim()
    },
    odd(a,b){
      this.odd = a.toUpperCase().trim()
    }
  },
  methods: {
    InpFocus(){
      let pFocus = document.getElementById("input");
        pFocus.focus();
        pFocus.select();
    },
    InpFocus1(){
      let pFocus = document.getElementById("input1");
        pFocus.focus();
        pFocus.select();
    },

    closeNewClerk(){
      this.$emit('saveNew_vs', this.inputSequence)
      this.header = ''
      this.barcode1 = ''
      this.barcode2 = ''
      this.codeData = []
      this.barcodeData = []
      this.total = 0
      this.originalData = {}
      // this.saveNew_vs()
      this.$emit('closeNewClerk')
    },
    sibling(e) {
      let s = []
      let pp = e.parentNode.parentNode.children
      console.log(pp)
      for (let j = 0; j < pp.length; j++) {
        let p = pp[j].children
        for(let i = 0, pl = p.length; i < pl; i++) {
          if(p[i] !== e) s.push(p[i])
        }
      }
      return s
    },
    // 输入不存在货号后，颜色，尺码赋值
    csAssignment(str){
      this.$message.info("货号未建档，准备建档...")
      if (this.brand == '') {
        this.$alert('品牌不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (this.name == '') {
        this.$alert('品名不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (this.vendorPrice == '') {
        this.$alert('厂商售价不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      // 货号里提取色号，色号获取颜色
      // styleColor款色， 色尺colorSize
      if (this.styleNumber && (this.manufacturerBarCode.styleNumber != this.styleNumber)) {
        this.manufacturerBarCode.styleNumber = this.styleNumber
      }
      console.log(this.manufacturerBarCode)
      console.log(str)
      let colorSize = str.slice(this.manufacturerBarCode.styleNumber).split('-')
      console.log(JSON.stringify(colorSize).replace(/\[|]/g ,''))
      let tmpLen = 0
      if (this.manufacturerBarCode.styleColorSize) {
        // 型尺色

        if (this.manufacturerBarCode.styleColor) {
          // 款号与尺码之间有 - 

          if (this.manufacturerBarCode.colorSize) {
            // 色号与尺码之间有 -        MCC-A0001-7-001   ["", "7", "001"]
            this.knSize = colorSize[1]
            this.colorNo = colorSize[2]
          } else {
            // 色号与尺码之间没有 -        MCC-A0001-7001    ["", "7001"]
            tmpLen = colorSize[0].length
            this.knSize = colorSize[1].slice(0,tmpLen-this.manufacturerBarCode.colorNumber)
            this.colorNo = colorSize[1].slice(tmpLen-this.manufacturerBarCode.colorNumber)
          }
        } else {
          // 款号与尺码之间没有 - 

          if (this.manufacturerBarCode.colorSize) {
            // 色号与尺码之间有 -      MCC-A00017-001    ["7", "001"]
            this.knSize = colorSize[0]
            this.colorNo = colorSize[1]
          } else {
            // 色号与尺码之间没有 -     MCC-A00017001    ["7001"]
            tmpLen = colorSize[0].length
            this.knSize = colorSize[0].slice(0,tmpLen-this.manufacturerBarCode.colorNumber)
            this.colorNo = colorSize[0].slice(tmpLen-this.manufacturerBarCode.colorNumber)
          }
        }
      } else {
        // 型色尺

        if (this.manufacturerBarCode.styleColor) {
          // 款号与颜色之间有 - 

          if (this.manufacturerBarCode.colorSize) {
            // 色号与尺码之间有 -     MCC-A0001-001-7   ["", "001", "7"]
            this.colorNo = colorSize[1]
            this.knSize = colorSize[2]
          } else {
            // 色号与尺码之间没有 -    MCC-A0001-0017   ["", "0017"]
            tmpLen = colorSize[0].length
            console.log(colorSize)
            console.log(this.manufacturerBarCode.colorNumber)
            this.colorNo = colorSize[1].slice(0,this.manufacturerBarCode.colorNumber)
            this.knSize = colorSize[1].slice(this.manufacturerBarCode.colorNumber)
          }
        } else {
          // 款号与颜色之间没有 - 

          if (this.manufacturerBarCode.colorSize) {
            // 色号与尺码之间有 -      MCC-A0001001-7      ["001", "7"]
            this.colorNo = colorSize[0]
            this.knSize = colorSize[1]
          } else {
            // 色号与尺码之间没有 -      MCC-A00010017     ["0017"]
            tmpLen = colorSize[0].length
            this.colorNo = colorSize[0].slice(0,this.manufacturerBarCode.colorNumber)
            this.knSize = colorSize[0].slice(this.manufacturerBarCode.colorNumber)
          }
        }
      }

      // console.log(this.colorNo)
      // console.log(this.knSize)

      const that = this

      Promise.all([
        getColorSeason({no:this.colorNo,limit:99999}),
        getSize({kind:this.manufacturerBarCode.sizeKindId, limit: 99999})
      ]).then(([r1, r2]) => {
        // console.log(r1)
        // console.log(r2)
        // 颜色
        if (r1.data.code == 200 && r1.data.data.length) {
          that.colorName = r1.data.data[0].name
        } else {
          return that.styleError(str)
        }
        // 尺码
        if (r2.data.code == 200 && r2.data.data) {
          let list = r2.data.data
          that.knAllSize = list
          let exist = 0
          for (const i of list) {
            if (i.size == that.knSize) {
              exist = 1
            }
            that.knSizeList[i.size] = i
          }
          if (!exist) {
            return that.styleError(str)
          }
        } else {
          return that.styleError(str)
        }

        that.createKN(str)
      }).catch(reason => {
        console.log(reason)
        that.$message.error("货号颜色或尺寸获取失败，货号建档失败")
      })
    },

    styleError(str){
      const newStyleNumber = str.slice(0,this.manufacturerBarCode.styleNumber)
      this.$alert(`根据 ${this.styleNumber} 款号位拆分，<br>
        款号：${newStyleNumber}，
        色号：${this.colorNo}，
        尺码：${this.knSize}；<br>
        颜色或尺寸不存在，请检查款号位填写是否正确`, '货号建档失败', {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true
      })
    },

    // 季度输入选择
    queryQuarterList(queryString, cb){
      cb(this.quarterList)
    },

    refreash(a){
      this.brand = ''
      this.brandList = []
      this.brandedCompany = ''
      // 厂商编号查找品牌公司
      getManufacturer({no:a,limit:99999}).then(res => {
        for (const i of res.data.data) {
          if (i.no == a) {
            this.brandedCompany = i.brandedCompany
            break
          }
        }

        // 品牌公司查条码规律详情
        getBarCode({company:this.brandedCompany}).then(res => {
          console.log(res)
          this.manufacturerBarCode = res.data.data[0]
          // 款号，色号，验证码，条码样式赋值
          console.log(this.manufacturerBarCode)
          this.styleNumber = this.manufacturerBarCode.styleNumber
          this.colorNumber = this.manufacturerBarCode.colorNumber
          this.code = this.manufacturerBarCode.code
          // this.radio = this.manufacturerBarCode.barCodeArticleNumberEqual ? '1' : '2'
        })

        // 品牌公司查品牌
        getBranded({brandedCompany: this.brandedCompany, limit: 9999}).then(res => {
          let num = 1
          res.data.data.forEach(e => {
            this.brandList.push({value:e.name,label:e.name})
            if (num) {
              if (!this.brand) this.brand = e.name
              num = 0
            }
          })
        })

        
        getColorSeason({brandedCompany:this.brandedCompany,limit:99999}).then(res => {
          if ((res.data.data.length)) {
            this.colorList = []
            res.data.data.forEach(e => {
              this.colorList.push({no:e.no, value:e.name})
            })
          }
        })
      })
    },
    // 厂商编号失去焦点
    manufacturerNoBlur(){
      let a = this.manufacturerNo
      this.styleNumber = ''
      this.colorNumber = ''
      this.code = ''
      if (a != '') {
        for (const i of this.manufacturerList) {
          if (this.manufacturerNo == i.value) {
            this.manufacturerName = i.label
            this.refreash(a)
            return
          }
        }
        this.$alert('无此厂商编号', '', {
          confirmButtonText: '确定'
        })
        this.manufacturerNo = ''
        this.manufacturerName = ''
      } else {
        this.manufacturerName = ''
      }
    },
    // 选择厂商
    manufacturerNameChange(e){
      this.manufacturerNo=e
      for(let b of this.manufacturerList){
        if(e == b.value){
          this.discount = b.discount
        }
      }
      this.refreash(this.manufacturerNo)
    },
    inputWarehouseNoBlur(){
      if (this.inputWarehouseNo != '') {
        for (const i of this.warehouseList) {
          if (this.inputWarehouseNo == i.value) {
            this.inputWarehouseName = i.label
            return
          }
        }
        this.$alert('无此仓库编号', '', {
          confirmButtonText: '确定'
        })
        this.manufacturerNo = ''
        this.manufacturerName = ''
      } else {
        this.manufacturerName = ''
      }
    },
    companyNoBlur(){
      if (this.companyNo != '') {
        for (const i of this.warehouseList) {
          if (this.companyNo == i.value) {
            this.companyName = i.label
            return
          }
        }
        this.$alert('无此仓库编号', '', {
          confirmButtonText: '确定'
        })
        this.companyNo = ''
        this.companyName = ''
      } else {
        this.companyName = ''
      }
    },
    colorNoBlur(){
      if (this.colorNo != '') {
        for (const i of this.colorList) {
          if (this.colorNo == i.no) {
            this.colorName = i.value
            return
          }
        }
        this.$alert('无此色号', '', {
          confirmButtonText: '确定'
        })
        this.colorNo = ''
        this.colorName = ''
      } else {
        this.colorName = ''
      }
    },


    // 继续录入
    continueInput(){
      if (!this.inputDate) {
        this.$alert('日期不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (!this.manufacturerNo) {
        this.$alert('厂商不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (!this.inputWarehouseNo) {
        this.$alert('收货仓库不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (!this.companyNo) {
        this.$alert('公司仓库不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (this.discount == '') {
        this.$alert('折数不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      // 之前输入货号录入1条
      let kindsNumberNumberMap = {}
      let rfidList = []
      let knList = []
      if (JSON.stringify(this.tmpData)!='{}' && this.isBarcode) {
        // console.log(this.tmpData)
        kindsNumberNumberMap[this.tmpData.kindsNumber] = this.tmpData.sum
      } else {
        // 之前输入款号录入多条
        // console.log(this.codeData)
        this.codeData.forEach(e => {
          let c = e.colorNo
          this.sizeList.forEach(f => {
            if (this.manufacturerBarCode.styleColorSize || this.manufacturerBarCode.styleColorSize == undefined) {
              // 型尺色

              if (this.manufacturerBarCode.styleColor) {
                // 款号与尺码之间有 - 

                if (this.manufacturerBarCode.colorSize) {
                  // 色号与尺码之间有 - 
                  knList.push({
                    kindsNumber:`${this.header}-${f}-${c}`,
                    sum:e[f]
                  })
                } else {
                  // 色号与尺码之间没有 -  
                  knList.push({
                    kindsNumber:`${this.header}-${f}${c}`,
                    sum:e[f]
                  })
                }
              } else {
                // 款号与尺码之间没有 - 

                if (this.manufacturerBarCode.colorSize) {
                  // 色号与尺码之间有 -  
                  knList.push({
                    kindsNumber:`${this.header}${f}-${c}`,
                    sum:e[f]
                  }) 
                } else {
                  // 色号与尺码之间没有 - 
                  knList.push({
                    kindsNumber:`${this.header}${f}${c}`,
                    sum:e[f]
                  })
                }
              }
            } else {
              // 型色尺

              if (this.manufacturerBarCode.styleColor) {
                // 款号与颜色之间有 - 

                if (this.manufacturerBarCode.colorSize) {
                  // 色号与尺码之间有 -  
                  knList.push({
                    kindsNumber:`${this.header}-${c}-${f}`,
                    sum:e[f]
                  })
                } else {
                  // 色号与尺码之间没有 -  
                  knList.push({
                    kindsNumber:`${this.header}-${c}${f}`,
                    sum:e[f]
                  })
                }
              } else {
                // 款号与颜色之间没有 - 

                if (this.manufacturerBarCode.colorSize) {
                  // 色号与尺码之间有 -  
                  knList.push({
                    kindsNumber:`${this.header}${c}-${f}`,
                    sum:e[f]
                  })
                } else {
                  // 色号与尺码之间没有 - 
                  knList.push({
                    kindsNumber:`${this.header}${c}${f}`,
                    sum:e[f]
                  }) 
                }
              }
            }
          })
        })
        // console.log(knList)
      }
      // 扫描货号或输入货号，isKindsNumber为true
      let isKindsNumber = !(this.isBarcode && this.radio==2)
      
      // 补单新增的货号放在kindsNumberNumberMap
      // 原有货号不管有没有修改数量，都将原来数据放在kindsNumberMap	

      if (isKindsNumber) {
        knList.forEach(e => {
          if (e.sum) {
            kindsNumberNumberMap[e.kindsNumber] = Number(e.sum)
          }
        })
      } else {
        rfidList = [{showCode: this.barcode1}]
      }

      // 补单把新增的都放在kindsNumberNumberMap，已有的数量不改放在kindsNumberMap

      let t = this.inputDate
      if (t.length == 10) {
        t += ' 12:00:00'
      }
      let dataSource = 1
      if (this.isBarcode && this.radio == 2) {
        dataSource = 0
      }
        let obj1 = {
          isScanner:true,
          isSame:false,
          searchValue: this.barcode1,
          kindsNumber:this.barcode2,
          sellPrice:this.vendorPrice,
       }
       let obj2 = {
         rfidValue:this.barcode1,
         kindsNumberValue:this.barcode2,
         sellPrice:this.vendorPrice
       }
      console.log(obj1)
      let Exp
      let state = ''
      if(this.isBarcode && this.radio == 2){
        console.log(obj2)
        factoryInputScanner(obj2).then(res=>{
          // console.log(res)
          if(res.data.data == null){
            document.getElementById('input').focus()
            this.$message('未找到此rfid，请输入货号')
            state = 1
            return
          }
        })
      }else{
        searchKindsNumber(obj1).then(res=>{
          // console.log(res)
          if(res.data.code == 200 && res.data.data != null){
            // console.log(this.barcodeData)
            this.barcode1 = ''
            this.InpFocus1()
            return
          }else{
            this.InpFocus()
          }
        })
      }
      
      
      let d = {
        manufacturerDTO: {
          dataSource,
          isNewBox: true,
          isKindsNumber,
          inputSequence : this.inputSequence,
          inputDate: t,
          manufacturerNo : this.manufacturerNo,
          odd : this.odd,
          inputWarehouseNo : this.inputWarehouseNo,
          companyNo : this.companyNo,
          cooperateWay : this.cooperateWay,
          kindsNumberNumberMap,
          kindsNumberMap: this.kindsNumberMap,
          discount: this.discount,
          flagToken:this.Str
        },
        rfidList
      }
      // console.log(d)
      this.loading = true
      factoryInput(JSON.stringify(d)).then(res => {
        // console.log(res)
        if (res.data.code == 200) {
          this.loading = false
          // this.$message({
          //   message: '保存成功',
          //   type: 'success'
          // })
          if(state == 1) return
          if (!this.creating) this.creating = true
          // if(res.data.data.totalDTO != null){
            if(res.data.data.validList == null){
              document.getElementById('input1').focus()
              this.barcode1 = ''
            }
            this.inputSequence = res.data.data.totalDTO.validList[0].sequence
            this.barcodeData = res.data.data.totalDTO.validList
            this.barcodeData.forEach(e => {
              e.oldMP = e.manufacturerPrice
            });
            if (!this.barcodeData.length) this.inputSequence = ''
            this.barcode1 = ''
            document.getElementById('input1').focus()
          // }
          this.barcode1 = ''
          this.barcode2 = ''
          this.header = ''
          this.codeData = []
          this.$refs.barcodeInput.focus()
          this.total = this.barcodeData.reduce((prev,next) => {
            return prev + Number(next.sum)
          },0)
          
          
          
          // 发送到父组件数据
          // this.$emit('saveNew_vs', send)
          if (res.data.data.errorDate && res.data.data.errorDate.length) {
            // 导出一个txt文本
            // console.log(String(res.data.data.errorDate))
            this.exportRaw(String(res.data.data.errorDate),'errorDate.txt')
          }
          
        } else {
          this.$message.error('保存失败')
          this.loading = false
        }
      })
    },
    
    // 扫描/输入货号或款号
    barcodeEnter1(e){
      if(this.manufacturerNo == '' || this.inputWarehouseNo == ''){
        this.$message.warning('厂商编号，收货仓库不能为空')
        return
      }
      if (this.barcode1) {
        if (!this.isBarcode) {
          // 手输款号
          getKindsNumberList({kindsNumberStr: this.barcode1}).then(res => {
            if (res.data.data.data.length) {
              this.header = res.data.data.data[0].styleNumber
              this.$emit('inpNumChange')
              // 品牌公司查条码规律详情
              getBarCode({company:res.data.data.data[0].brandedCompany}).then(res => {
                this.manufacturerBarCode = res.data.data[0]

                // 款号，色号，验证码，条码样式赋值
                this.brand = this.manufacturerBarCode.company
                this.styleNumber = this.manufacturerBarCode.styleNumber
                this.colorNumber = this.manufacturerBarCode.colorNumber
                this.code = this.manufacturerBarCode.code
                // this.radio = this.manufacturerBarCode.barCodeArticleNumberEqual ? '1' : '2'
              })
              // console.log(this.manufacturerBarCode)
              // 输入款号显示中间表和尺码信息   ZZZ-AAS
              res.data.data.data.sort((a,b) => {
                return a.relevanceSize.localeCompare(b.relevanceSize)
              })
              let tmp = res.data.data.data
              this.tmpBarcodeData = tmp
              // console.log(tmp)

              // 中间表  尺码表头
              this.sizeList = [tmp[0].size]
              // console.log(this.sizeList)
              let isExistSize = 0
              for (const i of tmp) {
                for (const j of this.sizeList) {
                  if (j == i.size) {
                    isExistSize = 0
                    break
                  }
                  isExistSize = 1
                }
                if (isExistSize) {
                  this.sizeList.push(i.size)
                }
              }

              // 中间表
              let tmpCodeData = [{colorNo:tmp[0].colorNo,colorName:tmp[0].colorName}]
              let isExistColor = 0
              for (const i of tmp) {
                for (const j of tmpCodeData) {
                  if (j.colorName == i.colorName) {
                    isExistColor = 0
                    break
                  }
                  isExistColor = 1
                }
                if (isExistColor) {
                  tmpCodeData.push({colorNo:i.colorNo,colorName:i.colorName})
                }
              }
              tmpCodeData.forEach(e => {
                this.sizeList.forEach(f => {
                  e[f] = ''
                })
              })
              this.codeData = tmpCodeData
              res.data.data.data.forEach(m => {
                // m.onePrice = (m.sellingPrice * m.discount / 10).toFixed(2)
                m.onePrice = m.sellingPrice
              })
              let codeTable = document.getElementById('codeTable')
              let inputs = codeTable.getElementsByTagName('input')
              // console.log(inputs)
              let int = setInterval(() => {
                clearInterval(int)
                inputs[0].focus()
                inputs[inputs.length - 1].onkeyup = e => {
                  if (window.event.keyCode == 13) {
                    this.continueInput()
                    inputs[inputs.length - 1].onkeyup = () => {}
                  }
                }
              }, 100)
            } else {
              this.$message('此货号/款号无数据')
              this.$refs.barcodeInput.focus()
            }
          })
        } else {
          // 有  验证码  的话  条码与货号   是一致
          if (this.radio == 2) {
            // 扫码id码
            if (this.manufacturerBarCode.code) {
              // 有验证码
              this.barcode2 = this.barcode1.slice(0, this.barcode1.length-this.manufacturerBarCode.code)
              // console.log(this.barcode1, ',', this.barcode2)
            }
            if (this.manufacturerBarCode.barCodeArticleNumberEqual) {
              this.barcodeEnter2()
            } else {
              // 货号和ID不一致
              this.$refs.barcodeInput1.focus()
            }
            return
          }

          // return
          
          let params = {
            // 条码与货号是否一致
            isSame: this.manufacturerBarCode.barCodeArticleNumberEqual == 1,
            // 是否开启条码扫描
            // isScanner: this.isBarcode,
            isScanner:false,
            kindsNumber: this.barcode1,
            searchValue: this.barcode1,
            sellPrice: this.vendorPrice
          }
          searchKindsNumber(params).then(res => {
            if (res.data.code == 200) {
              if (res.data.data) {
                // 货号建档已存在
                this.tmpData = res.data.data
                this.tmpData.sum = this.scanNum
                this.$refs.barcodeInput.focus()
                this.continueInput()
              } else {
                // 为空需要货号建档
                this.csAssignment(this.barcode1)
              }
            }
          })
        }
      }
    },
    barcodeEnter2(e){
      if (!this.barcode2) {
        // 为空
        this.continueInput()
        return
      }
      let obj2 = {
         rfidValue:this.barcode1,
         kindsNumberValue:this.barcode2,
         sellPrice:this.vendorPrice
       }
      console.log(obj2)
        factoryInputScanner(obj2).then(res=>{
          console.log(res)
          if (res.data.code == 200) {
            if (!res.data.data) {
              console.log(1)
              // 为空需要货号建档
              // console.log('返回值为空需要货号建档')
              this.csAssignment(this.barcode2)
            } else {
              // 货号建档已存在
              // console.log('货号存在')
              this.$refs.barcodeInput.focus()
              this.continueInput()
            }
          }
        })
    },

    // 货号建档
    createKN(str){
      let quarterID = this.quarterMap[this.quarter]
      if (!quarterID) {
        postQuarter({quarterName: this.quarter}).then(res => {
          quarterID = res.data.data
        })
      }
      for (const i of this.nameList) {
        if (this.name == i.value) {
          this.commodityType = i.commodityTypeNo
          break
        }
      }
      let newStyleNumber = str.slice(0,this.manufacturerBarCode.styleNumber)
      // let newStyleNumber = '000'
      getArtNo({
        pageSize: 9999,
        styleNumber: newStyleNumber,
        groupType: 1
      }).then(res => {
        let colorList = [{colorNo:this.colorNo,colorName:this.colorName}]
        // let sizeList = [this.knSize]
        if (res.data.code == 200 && res.data.data.length) {
          let list = res.data.data
          let hasColor = 0
          let hasSize = 0
          for (const i of list) {
            for (const c of colorList) {
              if (i.colorNo == c.colorNo) {
                hasColor = 0
                break
              }
              hasColor = 1
            }
            if (hasColor) {
              colorList.push({colorNo:i.colorNo,colorName:i.colorName})
            }

            // for (const s of sizeList) {
            //   if (i.size == s) {
            //     hasSize = 0
            //     break
            //   }
            //   hasSize = 1
            // }
            // if (hasSize) {
            //   sizeList.push(i.size)
            // }
          }
        }

        let cs = ''
        colorList.forEach(e => {
          if (cs) {
            cs += `,${e.colorNo}:${e.colorName}`
          } else {
            cs = e.colorNo + ':' + e.colorName
          }
        })

        // let ss = []
        // sizeList.forEach(e => {
        //   ss.push(this.knSizeList[e])
        // })



        let knP = {
          kindsNumber: {
            commodityName:this.name,
            commodityType: this.commodityType,
            styleNumber: newStyleNumber,
            brandedName: this.brand,
            brandedCompany: this.brandedCompany,
            colorName: cs,
            sellingPrice: this.vendorPrice,
            sellingPriceOne:this.vendorPrice,
            quarter: quarterID,
            supplier: this.manufacturerNo
          },
          sizeList: this.knAllSize
        }
        // console.log(knP)
        // return
        postKindsNumber(JSON.stringify(knP)).then(res => {
          if (res.data.code == 200) {
            // console.log('货号建档成功')
            this.$message.info("货号建档成功，准备厂进...")
            let params = {
              // 条码与货号是否一致
              // isSame: this.radio==1,
              isSame:true,
              // 是否开启条码扫描
              isScanner: this.isBarcode,
              kindsNumber: this.barcode2,
              searchValue: this.barcode2,
              sellPrice: this.vendorPrice
            }
            console.log(params)
            searchKindsNumber(params).then(res => {
              console.log(res)
              this.tmpData = res.data.data
              this.tmpData.sum = this.scanNum
              this.$refs.barcodeInput.focus()
              this.continueInput()
            })
          } else {
            this.$message.error("货号建档失败")
          }
        })
      })
    },

    //  输入回车/失去焦点统计
    //  index 行索引
    //  result 输入内容
    handleInputBlurResult(e,{index,key,result}) {
      e.target.parentNode.parentNode.parentNode.classList.remove('activeCell')
      let r = /^(0|[1-9][0-9]*|-[1-9][0-9]*)$/
      if (result != 0) {
        result = result.replace(/\b(0+)/gi,"")
      }
      if (!r.test(result) && result) {
        this.$alert('数量请输入整数', '', {
          confirmButtonText: '确定'
        })
        if (this.codeData[index]) {
          this.codeData[index][key] = 0
        }
        return
      }
      if (this.codeData[index]) {
        this.codeData[index][key] = result
      }
    },
    cellClick(_row, _column, cell, _event){
      // console.log(row)  //当行的全部数据
      // console.log(column)  //当列的全部数据
      // console.log(cell)  //点击格的html代码  td>div
      // console.log(event)  //MouseEvent
      // console.log(cell.innerHTML)

      // console.log(cell.children[0].children[0].children)
      // cell.children[0].children[0].children[0].focus()
      cell.classList.add('activeCell')
      let s = this.sibling(cell)
      // console.log(s)
      s.forEach(e => {
        e.classList.remove('activeCell')
      })
    },
    inpEnter(e){
      e.target.parentNode.parentNode.parentNode.classList.remove('activeCell')
    },


    closePopup(){
      this.showPopup = 'none'
      this.scanNum = this.beforeScanNum
    },
    // 扫描数量确定   MCC-A00-S-001
    determine(){
      this.showPopup = 'none'
    },

    mpBlur(row) {
      const price = row.manufacturerPrice.toString().trim()
      let r = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/
      if (!r.test(price) && price != '0') {
        this.$message.error('金额格式不正确')
        return
      }
      if (row.oldMP == price) return
      // console.log('kkkkkkkkkkkk');
      // return
      updateMP({
        kindsNumber: row.kindsNumber,
        price,
        sequence: row.sequence,
      }).then(res => {
        if (res.data.code != 200) {
          this.$message.error('厂价修改失败')
          row.manufacturerPrice = row.oldMP
        } else {
          row.oldMP = row.manufacturerPrice
        }
      })
    }
  },
  mounted(){
    let _this = this
    document.onkeydown = function(event){
      let e = event || window.event || arguments.callee.caller.arguments[0]
      if(e && e.keyCode==118){ // 按 F7
        // console.log('an f7')
        if(_this.showPopup == 'none'){
          _this.beforeScanNum = _this.scanNum
          _this.showPopup = 'block'
        }else{
          _this.showPopup = 'none'
        }
      }
    }
  }
}
</script>

<style scoped>
  /* 新建资料 */
  .mask{
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: #000;
    opacity: 0.3;
    z-index: 9;
  }
  .new_vs{
    position: fixed;
    top: 5%;
    left: 50%;
    transform: translateX(-50%);
    width: 1070px;
    z-index: 99;
    background-color: white;
    overflow: auto;
  }
  .new_vs .vs-top{
    height: 40px;
    background-color: #f8f8f8;
  }
  .new_vs .vs-top p{
    float: left;
    line-height: 40px;
    padding-left: 20px;
    font-weight: 700;
  }
  .new_vs .vs-top i{
    float: right;
    line-height: 40px;
    padding: 0 16px;
  }

  .new_vs input{
    height: 30px;
    border: solid 1px #DCDFE6;
    border-radius: 5px;
    margin-left: 10px;
  }
  .new_vs input:focus{
    outline: none;
    border: solid 1px #409EFF;
  }
  .new_vs .vs-info-2 .inp-2{
    margin-right: 15px;
  }
  
  .vs-info{
    padding: 0 15px;
    padding-bottom: 10px;
    /* border-bottom: solid #f2f2f2 2px; */
  }
  .vs-info-1 p,.vs-info-2 p{
    display: inline-block;
    width: 80px;
    text-align: right;
    margin-right: 15px;
  }
  .vs-info-1 p:nth-child(3){
    margin-left: 10px;
  }
  .new_vs .vs-info-1 .inp-2{
    margin-right: 43px;
  }
  .vs-info .vs-info-2{
    margin-bottom: 15px;
  }
  .vs-info .barcode p{
    display: inline;
    margin-right: 15px;
  }
  .vs-info .barcode div{
    margin-top: 15px;
  }

  .barcode-info-1 p, .barcode-info-2 p{
    display: inline-block;
    width: 80px;
    text-align: right;
    margin-right: 9px;
  }
  .barcode-info-1 p:first-child, .barcode-info-2 p:first-child{
    width: 40px;
  }
  .colorBox, .infoBox {
    display: inline;
  }

  .enterBarcode{
    height: 60px;
    background-color: #f2f2f2;
    margin: 15px 0;
  }

  .vs-btn{
    float: right;
    margin: 0 15px 15px;
  }

  .popup{
    width: 400px;
    height: 200px;
    border: 2px solid #f4f4f4;
    box-shadow: 0 2px 2px 2px #dbdbdb;
    z-index: 999;
    position: absolute;
    left: 50%;
    top: 50%;
    margin:-100px 0 0 -200px;
    background: white;
    display: block;
  }
  .popup_t{
    display: flex;
    justify-content: space-between;
    width: 100%;
    height: 40px;
    background: rgb(244, 244, 244);
    padding: 8px 15px;
  }
  .popup_t p{
    font-weight: 700;
  }
  .popup_c{
    padding: 8px 15px;
  }
  .popup_button{
    margin: 5px 0 0 0;
    width: 94%;
    height: 30px;
    padding:0 10px;
    border: 2px solid #f4f4f4;;
    border-radius: 3px;
  }
  .popup_b{
    margin: 10px 0 0 0;
    padding-left: 230px;
  }
  .shortInp {
    width: 70px!important;
  }
  .longInp {
    width: 230px!important;
  }
</style>

<style>
  .new_vs .vs-info-1 .el-input, .new_vs .vs-info-2 .el-input{
    /* margin: 10px 20px 0 10px; */
    margin-top: 10px;
    width: 160px;
  }
  .new_vs .el-input__inner{
    height: 30px!important;
  }
  .new_vs .el-input__icon{
    line-height: 30px!important;
  }
  .vs-info .barcode .el-switch{
    margin: 0!important;
  }
  .new_vs .barcode-info-1 .el-input, .new_vs .barcode-info-2 .el-input{
    /* margin: 10px 0 0 10px; */
    margin-top: 10px;
    width: 160px;
  }

  .new_vs .enterBarcode .el-input{
    width: 350px;
    margin: 14px 17px;
  }

  .new_vs .colorBox .el-input{
    width: 60px;
    margin-right: 10px;
  }
  .new_vs .vs-info-1 .infoBox .el-input, .new_vs .vs-info-2 .infoBox .el-input{
    margin: 0 10px 0 0;
    width: 60px;
  }
  .new_vs .vs-info-1 .infoBox .el-input--suffix, .new_vs .vs-info-2 .infoBox .el-input--suffix{
    width: 90px;
  }
  .new_vs .colorBox .el-input--suffix{
    width: 90px;
  }

  
</style>
